<template>
  <div>
    <div id="count">{{count.num}}</div>
    <button @click="update">update</button>
    <button @click="unwatch">停止监听</button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
const count = reactive({ num: 1 })
const printNumAsync = (v: number) => {
  return setTimeout(() => {
    console.log('打印新值' + v)
  }, 2000)
}
// 监听一个getter函数的返回值
// watch的返回值是一个停止监听的函数，调用之后，这个watch就没用了
const unwatch = watch(() => count.num, (newVal, oldVal, onCleanup) => {
  // 异步打印操作就是一个副作用
  const timer = printNumAsync(newVal)
  // onCleanup会在下一次值改变之前触发，在这里面可以清除副作用也就是清除上面的异步任务
  onCleanup(() => {
    clearTimeout(timer)
    console.log('执行下一次异步操作前，这个清理副作用的函数会执行')
  })
  console.log(newVal, oldVal)
  const el = document.querySelector('#count') as HTMLDivElement
  console.log(el?.innerHTML)
}, {
  immediate: true,
  flush: 'post'
})

const name1 = ref('rose')
const color1 = ref('red')

// 写一个数组的ref
watch([name1, color1], ([newName, newColor], [oldName, oldColor]) => {
  console.log(newName, oldName)
  console.log(newColor, oldColor)
})

const state = reactive({ count: 0 })
watch(
  state,
  (newValue, oldValue) => {
    // newValue === oldValue
    console.log(newValue, oldValue)
  }
)

const update = () => {
  count.num += 1
  name1.value = name1.value + '❤️'
  color1.value = color1.value + '❤️'
  state.count += 1
}

</script>

<style scoped>

</style>
